// eslint-disable-next-line import/no-extraneous-dependencies
const { validate } = require('schema-utils');
const { tplReplace } = require('../utils');

const schema = {
  type: 'object',
  properties: {
    log: {
      type: 'boolean',
    },
  },
  additionalProperties: false, // 是否允许不存在的选项传入
};

function tplLoader(source) {
  const resource = source.replace(/\s+/g, '');
  const options = this.getOptions();
  validate(schema, options, {
    name: 'tpl-loader',
    baseDataPath: 'options',
  });
  const logStr = options.log ? `console.log('Compiled the file from ${this.resourcePath}')` : '';

  return `
    export default (data) => {
      ${tplReplace.toString()}
      ${logStr}
      return tplReplace('${resource}', data);
    }
  `;
}

module.exports = tplLoader;
